package org.ldx.lotterysystem.service.activitystatus.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.ldx.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import org.ldx.lotterysystem.common.exception.ServiceException;
import org.ldx.lotterysystem.controller.param.DrawPrizeParam;
import org.ldx.lotterysystem.service.ActivityService;
import org.ldx.lotterysystem.service.activitystatus.ActivityStatusManager;
import org.ldx.lotterysystem.service.activitystatus.operator.AbstractActivityOperator;
import org.ldx.lotterysystem.service.dto.ConvertActivityStatusDTO;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 帘低晓露湿
 * @date 2025/11/13 10:58
 */
@Slf4j
@Component
public class ActivityStatusManagerImpl implements ActivityStatusManager {
    @Resource //为MAP赋值 因为只是工具类，所以可以用这种方式进行初始化
    private final Map<String, AbstractActivityOperator> operatorMap = new HashMap<>();
    @Resource
    ActivityService activityService;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleEvent(ConvertActivityStatusDTO convertActivityStatusDTO) {
        /**
         * 设计模式：
         * 1.责任链模式(按序)
         * 2.策略模式（sequence）
         */

        if(CollectionUtils.isEmpty(operatorMap)){
            log.info("operatorMap 为空");
            return;
        }
        Map<String,AbstractActivityOperator> currmap = new HashMap<>(operatorMap);
        //update  标志 判断是否需要更新缓存
        Boolean update = false;
        //先处理：人员，奖品
        update = processConvertStatus(convertActivityStatusDTO,currmap,1);
        //后处理：活动
        if(update){
            processConvertStatus(convertActivityStatusDTO,currmap,2);
        }else {
            update = processConvertStatus(convertActivityStatusDTO,currmap,2);
        }
        //更新缓存
        if(update){
            activityService.cacheActivity(convertActivityStatusDTO.getActivityId());
        }
    }

    @Override
    public void rollbackHandlerEvent(ConvertActivityStatusDTO convertActivityStatusDTO ) {
        // operatorMap：活动、奖品、人员
        for (AbstractActivityOperator operator : operatorMap.values()) {
            operator.convert(convertActivityStatusDTO);
        }

        // 缓存更新
        activityService.cacheActivity(convertActivityStatusDTO.getActivityId());
    }

    private Boolean processConvertStatus(ConvertActivityStatusDTO convertActivityStatusDTO,
                                         Map<String, AbstractActivityOperator> currMap,
                                         int sequence) {
        Boolean update = false;
        //遍历currMap
        Iterator<Map.Entry<String, AbstractActivityOperator>> it = currMap.entrySet().iterator();
        while (it.hasNext()){
            AbstractActivityOperator operator = it.next().getValue();
            //Operator是否需要转换
            if(operator.sequence()!=sequence
            ||!operator.needConvert(convertActivityStatusDTO)){
                //两种条件满足其一则不需要进行转换
                continue;
            }
            //转换
            if(!operator.convert(convertActivityStatusDTO)){
                log.error("{}转换失败！",it.getClass().getName());
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_CONVERT_ERROR);
            }
            //currMap 删除当前的Operator
            it.remove();
            update = true;

        }

        //返回
        return update;


    }
}
